//
//  PKPlayerManager.m
//  AVPlayer
//
//  Created by lanou on 15/10/5.
//  Copyright (c) 2015年 李伟伟. All rights reserved.
//

#import "PKPlayerManager.h"
#import <AVFoundation/AVFoundation.h>
@interface PKPlayerManager ()
@property(nonatomic, strong)NSArray *musicArray;//用来保存音乐地址的数组
@property(nonatomic, strong)AVPlayer *avPlayer;//音乐播放器
@property(nonatomic, assign)NSInteger playIndex;  //当前播放音乐的下标(不能有负数，NSUInteger)
@end

@implementation PKPlayerManager




-(instancetype)init
{
    self = [super init];
    if (self) {
        _avPlayer = [[AVPlayer alloc]init];
    }
    return self;
}

+(instancetype)sharedManager
{
    static PKPlayerManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[PKPlayerManager alloc]init];
    });
    return manager;
}

//给音乐播放器设置播放音乐的地址的数组
-(void)setManagerMusicArray:(NSArray *)array
{
    _musicArray = array;
}
//根据外界传过来的下标播放
-(void)playWithIndex:(NSInteger)index
{
    _playIndex = index;
    //根据传过来的下标 选择响应的播放地址
    NSURL *musicURL = [NSURL URLWithString:_musicArray[index]];
    AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:musicURL];
    //把播放器里的音乐地址 替换为新的地址
    [_avPlayer replaceCurrentItemWithPlayerItem:item];
    [_avPlayer play];
}
//下一首
-(void)nextOne
{
    _playIndex++;
    if (_playIndex == _musicArray.count) {
        _playIndex = 0;
    }
    //如果是随机播放模式  随机给一个下标
    if (_playType == PlayTypeRandom) {
        _playIndex = arc4random() % _musicArray.count;
    }
        [self playWithIndex:_playIndex];
}

-(void)lastOne
{
    _playIndex--;
    if (_playIndex < 0 ) {
        _playIndex = _musicArray.count- 1;
    }
    //如果是随机播放模式  随机给一个下标
    if (_playType == PlayTypeRandom) {
        _playIndex = arc4random() % _musicArray.count;
    }
    [self playWithIndex:_playIndex];
}

-(void)pauseAndPlay
{
    //AVPlayer当前的状态 0.0代表停止状态 1.0代表正在播放
    if (_avPlayer.rate == 0.0) {
        [_avPlayer play];
    }else
    {
        [_avPlayer pause];
    }
}

-(NSUInteger)totalTime
{
    CMTime time = _avPlayer.currentItem.duration;
    if (time.timescale == 0) {
        return 0;
    }
    return time.value/time.timescale;
}

-(NSUInteger)currentTime
{
    CMTime time = _avPlayer.currentTime;
    if (time.timescale == 0) {
        return 0;
    }
    return time.value/time.timescale;
}

-(void)goToTime:(NSUInteger)time
{
    CMTime newTime = _avPlayer.currentTime;
    newTime.value = newTime.timescale * time;
    [_avPlayer seekToTime:newTime];
}

-(void)stop
{
    [self goToTime:0];
    [_avPlayer pause];
}

@end
